package org.insia.smartposse.struts.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.insia.smartposse.config.DAOFactory;
import org.insia.smartposse.idao.ICompanyDAO;
import org.insia.smartposse.idao.IFreelanceDAO;
import org.insia.smartposse.idao.IProjectDAO;
import org.insia.smartposse.metier.Company;
import org.insia.smartposse.metier.Freelance;
import org.insia.smartposse.metier.Project;
import org.insia.smartposse.metier.User;
import org.insia.smartposse.utils.ActionUtils;
/**
 * Action for creating and modifying a project.
 * @author Patrick Ferreira and Sok hout SAO
 *
 */
public class CreateProjectAction extends DispatchAction {
	
	protected final Logger log = Logger.getLogger(CreateProjectAction.class);
	/**
	 * Show a new project creation
	 */
    @Override
	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	throws Exception {
    	Project project = new Project(-1, 0, "", null, null, "", (User)request.getSession().getAttribute("user"), "");
		request.setAttribute("project", project);
		request.setAttribute("messages", new String[]{});
		return mapping.findForward("show");
	}
    
    /**
     * Delete a project.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
       	Freelance freelance = (Freelance)request.getSession().getAttribute("freelance");
       	Company company = (Company)request.getSession().getAttribute("company");
       	
       	Project project = DAOFactory.getProjectDAO().get(ActionUtils.getLong(request, "id", -1L, null, null));
    	DAOFactory.getProjectDAO().delete(project);

		IFreelanceDAO fDao = DAOFactory.getFreelanceDAO();
		ICompanyDAO cDao = DAOFactory.getCompanyDAO();

		if (freelance != null) {
			freelance.getProjectSet().remove(project);
			fDao.update(freelance);
    		//request.getSession().setAttribute("user", freelance);
		} else {
			company.getProjectSet().remove(project);
			cDao.update(company);
			//request.getSession().setAttribute("user", company);
		}		
    	return mapping.findForward("success");    	
    }
    /**
     * Show a project's edition
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
    	Project project = DAOFactory.getProjectDAO().get(ActionUtils.getLong(request, "id", -1L, null, null));
		request.setAttribute("project", project);
		request.setAttribute("messages", new String[]{});
		
		return mapping.findForward("show");    	
    }
    /**
     * Create a project in database
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
	public ActionForward createProject(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
    	// initialisation de la liste des mesages d'erreurs
    	List<String> messages = new ArrayList<String>();
    	request.setAttribute("messages", messages);
       	Freelance freelance = (Freelance)request.getSession().getAttribute("freelance");
       	Company company = (Company)request.getSession().getAttribute("company");
       	User creator = (User)(freelance != null ? freelance : company);
       	
    	// recupération des données
    	long id = ActionUtils.getLong(request, "id", -1L, messages, "project.error.id");
    	long budget = ActionUtils.getLong(request, "budget", 0L, null, "");
    	String title = ActionUtils.getString (request, "title", "", messages, "project.error.title");
    	Date start_date = ActionUtils.getDate(request, "start_date", null, messages, "project.error.start_date");
    	SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
    	Date defaultDate = sdf.parse("0000-00-00");
    	Date end_date = ActionUtils.getDate(request, "end_date", defaultDate, null, "");
    	String description = ActionUtils.getString(request, "description", "", null, "");
 
    	String url = ActionUtils.getString(request, "url", "", null, "");
    	
    	Project project;
    	
    	// S'il y a eu des erreurs
    	if (messages.size() > 0) {
    		project = new Project(id,budget,title,start_date,end_date,description,creator,url);
    		request.setAttribute("project", project);
    		return mapping.findForward("failure");
    	}
    	
		IProjectDAO dao = DAOFactory.getProjectDAO();
		IFreelanceDAO fDao = DAOFactory.getFreelanceDAO();
		ICompanyDAO cDao = DAOFactory.getCompanyDAO();
		
    	// Si creation de nouveau project.
    	if (id == -1L) {
    		if (freelance != null) {
        		project = new Project(id,budget,title,start_date,end_date,description,(User)freelance,url);
    			dao.create(project);
    			freelance.getProjectSet().add(project);
    			//fDao.update(freelance);
        		//request.getSession().setAttribute("user", freelance);
    		} else {
        		project = new Project(id,budget,title,start_date,end_date,description,(User)freelance,url);
    			dao.create(project);
    			company.getProjectSet().add(project);
    			//cDao.update(company);
        		//request.getSession().setAttribute("user", company);
    		}    		
    		request.setAttribute("msgTitleKey", "project.createSuccessTitle");
    		request.setAttribute("msgLabelKey", "project.createSuccessLabel");
    	} else {
    		//Sinon modification de project
    		project = dao.get(id);
    		project.setParams(id,budget,title,start_date,end_date,description,creator,url);
    		dao.update(project);
    		if (freelance != null) {
    			fDao.update(freelance);
        		//request.getSession().setAttribute("user", freelance);
    		} else {
    			cDao.update(company);
    			//request.getSession().setAttribute("user", company);
    		}
    		
    		request.setAttribute("msgTitleKey", "project.updateSuccessTitle");
    		request.setAttribute("msgLabelKey", "project.updateSuccessLabel");
    	}
    	
    	return mapping.findForward("success");
    }
}